package com.foosun.core.filter;

import com.foosun.core.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SessionFilter implements Filter {

    public static final String USER = "user";

    private String longinUrl;

    private String[] excepUrl;


    @Override
    public void init(FilterConfig cfg) throws ServletException {
        excepUrl = cfg.getInitParameter("excepUrl").split(",");
        longinUrl = cfg.getInitParameter("longinUrl");
    }


    @Override
    public void destroy() {
    }


    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) arg0;
        HttpServletResponse resp = (HttpServletResponse) arg1;
//        String path = req.getServletPath();
//        if (path.indexOf(".") > -1 || path.equals(longinUrl) || isExcepUrl(path)) {
//            chain.doFilter(req, resp);
//            return;
//        }
//
//        User user = (User) req.getSession().getAttribute(USER);
//        if (user == null || path.equals("/") || path.equals("")) {
//            resp.sendRedirect(req.getContextPath() + longinUrl);
//            return;
//        }
        chain.doFilter(req, resp);
    }

    private boolean isExcepUrl(String path) {
        for (String url : excepUrl) {
            if (url.contains("*")) {
                url = url.substring(0, url.indexOf("*"));
                if (path.startsWith(url)) {
                    return true;
                }
            } else if (url.equals(path)) {
                return true;
            }
        }
        return false;
    }


}
